<?php

class Admin_PageController extends Kieumau_Controller_Admin
{

    public function init()
    {
    	parent::init();
	}
    
	public function indexAction(){
		$this->_redirect($this->getRequest()->getModuleName(). '/' . $this->getRequest()->getControllerName().'/list');
	}
	
	public function listAction(){
		$this->view->mainMenu = "Page";
		$this->view->subMenu = "";
		
		$pageTable = new Admin_Model_DbTable_Page();
		
		try{
			$newsList = $pageTable->getAllPage();
		
			$page = $this->_getParam ( 'page', 1 );
			$paginator = Zend_Paginator::factory ( $newsList );
			$paginator->setItemCountPerPage ( 4 );
			$paginator->setCurrentPageNumber ( $page );
			$this->view->newsList = $paginator;
		}catch(Exception $ex){
			echo $ex->getMessage();
			exit;
		}
	}
	
	public function addAction(){
		$this->view->mainMenu = "Page";
		$this->view->subMenu = "";
		
		if($this->getRequest()->isPost()){
			$formData = $this->getRequest()->getPost();
			$validateParams = array('course'=>'setSelectRequired', 'category'=>'setSelectRequired',  'name'=>'setRequired', 'excerpt'=>'setRequired', 'content'=>'setRequired');
			$error = $this->formValidate($formData, $validateParams);
			
			// If there's no error, The system will save data into database
			if(count($error)==0){
				
				//Xử lý upload image
				$folderName = 'pages/';
				if (! empty ( $_FILES ['represent_image'] ['name'] )) {
					$newname = $this->changename ( $_FILES ['represent_image'] ['name'], 'pages' );
					try {
						move_uploaded_file ( $_FILES ['represent_image'] ['tmp_name'], SYSTEM_FOLDER_PATH . $folderName . $newname );
						$formData['represent_image']= $folderName.$newname;
					} catch ( Exception $ex ) {
						echo "Failed to upload file, error :" . $ex->getMessage ();
						exit;
					}
						
					//Delete the old file
					$file_url = SYSTEM_FOLDER_PATH . $folderName . $formData ['represent_image_old'];
					$datontai = file_exists ( $file_url );
					if ($datontai) {
						if (is_file ( $file_url )) { //Check again to be sure 100%
							$file_url_real = SYSTEM_FOLDER_PATH . $folderName . $formData ['image_url_old'];
							unlink ( $file_url_real );
						}
					}
				}//END if !empty...
				else{
					if(!empty($formData['represent_image_old']))
						$formData['represent_image'] = $formData['represent_image_old'];
				}
				
				
				//Validation data again, remove unnessessary field
				$taxonomyId = $formData['taxonomy'];
				$categoryId = $formData['category'];
				unset($formData['taxonomy'], $formData['category']);
				
				//Set enabled for this page
				$formData['enabled'] = 1;
				
				$commonTable = new Admin_Model_DbTable_Page();
				$id = $commonTable->insertTable($formData);//Insert main table
				
				//Insert to page_category table
				try{
					$data = array('page_id'=>$id, 'category_id'=>$categoryId, 'taxonomy_id'=>$taxonomyId);
					$pageCategoryTable = new Admin_Model_DbTable_PageCategory();
					$pageCategoryTable->insert($data);
					$this->_redirect('admin/page');
				}catch(Exception $ex){
					echo $ex->getMessage();
				}
				
				//redirect to list page
				$this->_redirect('admin/'.$this->getRequest()->getControllerName());
			
			}else{//if exists error, fill form again and notice error
				$this->view->formData = $formData;
				$this->view->error = $error;
				if(!empty($formData['taxonomy'])){
					$this->view->taxonomyList = $this->getTaxonomyAsDropdown($formData['taxonomy']);//Create Type List With data from Form
					if(!empty($formData['category'])){
						$this->view->categoryList = $this->getCategoryByTaxonomyId($formData['taxonomy'], $formData['category']);
					}else{
						$this->view->categoryList = $this->getCategoryByTaxonomyId($formData['taxonomy']);
					}
				}else{
					$this->view->taxonomyList = $this->getTaxonomyAsDropdown();//Create Type List As Normal
				}
			}
		}else{
			$this->view->taxonomyList = $this->getTaxonomyAsDropdown();//Create Type List
		}
	}
	
    public function editAction(){
    	$this->view->mainMenu = "Page";
    	$this->view->subMenu = "";
    	
    	$id = $this->getRequest()->getParam('id',0);
    	$pageTable = new Admin_Model_DbTable_Page();
    	
    	if($this->getRequest()->isPost()){
    		
    		$formData = $this->getRequest()->getPost();
    		$validateParams = array('course'=>'setSelectRequired', 'category'=>'setSelectRequired',  'name'=>'setRequired', 'excerpt'=>'setRequired', 'content'=>'setRequired');
    		$error = $this->formValidate($formData, $validateParams);
    			
    		// If there's no error, The system will save data into database
    		if(count($error)==0){
    		
    			//Xử lý upload image
    			$folderName = 'pages/';
    			if (! empty ( $_FILES ['represent_image'] ['name'] )) {
    				$newname = $this->changename ( $_FILES ['represent_image'] ['name'], 'pages' );
    				try {
    					move_uploaded_file ( $_FILES ['represent_image'] ['tmp_name'], SYSTEM_FOLDER_PATH . $folderName . $newname );
    					$formData['represent_image']= $folderName.$newname;
    				} catch ( Exception $ex ) {
    					echo "Failed to upload file, error :" . $ex->getMessage ();
    					exit;
    				}
    		
    				//Delete the old file
    				$file_url = SYSTEM_FOLDER_PATH . $folderName . $formData ['represent_image_old'];
    				$datontai = file_exists ( $file_url );
    				if ($datontai) {
    					if (is_file ( $file_url )) { //Check again to be sure 100%
    						$file_url_real = SYSTEM_FOLDER_PATH . $folderName . $formData ['image_url_old'];
    						unlink ( $file_url_real );
    					}
    				}
    			}//END if !empty...
    			else{
    				if(!empty($formData['represent_image_old']))
    					$formData['represent_image'] = $formData['represent_image_old'];
    			}
    		
    		
    			//Validation data again, remove unnessessary field
    			$taxonomyId = $formData['course'];
    			$categoryId = $formData['category'];
    			unset($formData['course'], $formData['category']);
    			
    			//Insert main table
    			$commonTable = new Admin_Model_DbTable_Page();
    			$id = $commonTable->updateTable($formData, $id);
    		
    			//Insert to page_category table
    			$data = array('taxonomy_id'=>$taxonomyId,'category_id'=>$categoryId);
    			
    			$pageCategoryTable = new Admin_Model_DbTable_PageCategory();
    			$pageCategoryTable->update($data, "page_id = $id");
    			
    			$this->_redirect('admin/'.$this->getRequest()->getControllerName());
    		}else{//if exists error, fill form again and notice error
    			$this->view->formData = $formData;
    			$this->view->error = $error;
    			if(!empty($formData['course'])){
    				$this->view->taxonomyList = $this->getTaxonomyAsDropdown($formData['course']);//Create Type List With data from Form
    				if(!empty($formData['category'])){
    					$this->view->categoryList = $this->getCategoryByTaxonomyId($formData['course'], $formData['category']);
    				}else{
    					$this->view->categoryList = $this->getCategoryByTaxonomyId($formData['course']);
    				}
    			}else{
    				$this->view->taxonomyList = $this->getTaxonomyAsDropdown();//Create Type List As Normal
    			}
    		}
    		
    		
    		
    	}else{//Not a post
    		$formData = $pageTable->getAllByTable('id = '.(int)$id);
    		$this->view->formData = $formData[0];
    	
    		//Get Category of this page
    		$pageCategoryTable = new Admin_Model_DbTable_PageCategory();
    		$pageCategory = $pageCategoryTable->getByPageId($id);
    		
    		//Get Taxonomy of this category
    		//Create taxonomyList
    		$this->view->taxonomyList = $this->getTaxonomyAsDropdown($pageCategory['taxonomy_id']);
    		
    		//Create categoryList
    		$this->view->categoryList = $this->getCategoryByTaxonomyId($pageCategory['taxonomy_id'], $pageCategory['category_id']);
    	}
    }

    public function deleteAction(){
    	$this->_helper->layout->disableLayout ();
    	$this->_helper->viewRenderer->setNoRender ();
    	
    	if($this->getRequest()->isPost()){
    		$id = $this->getRequest()->getPost('id');
    		$newsTable = new Admin_Model_DbTable_Page();
    		$newsTable->deleteTableLanguage($id);
    	}
    }
    
    public function activateAction(){
    	$this->_helper->layout->disableLayout ();
    	$this->_helper->viewRenderer->setNoRender ();
    	if($this->getRequest()->isPost()){
    		$id = $this->getRequest()->getPost('id');
    		$pageTable = new Admin_Model_DbTable_Page();
    		$pageTable->activate($id);
    	}
    }
    
    public function getCategoryByTaxonomyId($taxonomyId, $selectedValue = ''){
    	$languageTableContent = $this->language->getLanguageDefault();//Get default Language Row
    		
    	$params = array('tableName'=>'category_language',//Tên table
    			'where'=>'lang_id = ? AND category_id in (SELECT category_id FROM category_taxonomy WHERE taxonomy_id = ?)',//Điều kiện lọc
    			'params'=>array($languageTableContent['id'], $taxonomyId),//Tham số truyền vào cho where
    			'value'=>'category_id',//Trường muốn làm value, trong select
    			'text'=>'name'//Trường muốn làm text, trong select
    	);
    	
    	//assign to view
    	return $this->createSelectCtrller($params , $selectedValue);
    }
    
	public function getTaxonomyAsDropdown($selectedValue = ''){
		$languageTableContent = $this->language->getLanguageDefault();//Get default Language Row
		 
		$params = array('tableName'=>'taxonomy_language',//Tên table
				'where'=>'lang_id = ?',//Điều kiện lọc
				'params'=>array($languageTableContent['id']),//Tham số truyền vào cho where
				'value'=>'taxonomy_id',//Trường muốn làm value, trong select
				'text'=>'name'//Trường muốn làm text, trong select
		);
		 
		return $this->createSelectCtrller($params , $selectedValue);
	}
	
	public function getpagelistAction(){
		$this->_helper->layout->disableLayout ();
// 		$this->_helper->viewRenderer->setNoRender ();
		
		//get taxonomy id
		$taxonomyId = $this->getRequest()->getParam('id');
		
		//get category inside
		$languageTableContent = $this->language->getLanguageDefault();//Get default Language Row
			
		$params = array('tableName'=>'category_language',//Tên table
				'where'=>'lang_id = ? AND category_id in (SELECT category_id FROM category_taxonomy WHERE taxonomy_id = ?)',//Điều kiện lọc
				'params'=>array($languageTableContent['id'], $taxonomyId),//Tham số truyền vào cho where
				'value'=>'category_id',//Trường muốn làm value, trong select
				'text'=>'name'//Trường muốn làm text, trong select
		);
		
		//assign to view
		$this->view->categoryList = $this->createSelectCtrller($params , '');
// 		echo "<pre>";
// 		var_dump($this->view->categoryList);
// 		echo "</pre>";
// 		exit;
	}
    
//Remove After Finish
    
    //return as String
    public function getNewsTypeAsDropdown($selectedValue = ''){
    	
    	$languageTableContent = $this->language->getLanguageDefault();//Get default Language Row
    	
    	$params = array('tableName'=>'news_type_language',//Tên table
    			'where'=>'id_lang = ?',//Điều kiện lọc
    			'params'=>array($languageTableContent['id']),//Tham số truyền vào cho where
    			'value'=>'id',//Trường muốn làm value, trong select
    			'text'=>'name'//Trường muốn làm text, trong select
    	);
    	
    	return $this->createSelectCtrller($params , $selectedValue);
    }
    
}
